<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { message } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './file.data';
  import { getCategoryList, createCategory, updateCategory } from '@/api/app/uploadPictures';

  export default defineComponent({
    name: 'FileModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          rowId.value = data.node.id;
          setFieldsValue({
            ...data.node,
          });
        }

        // 获取分类列表
        const treeData = (await getCategoryList()).list;
        const aaaa = [{ id: 0, pid: 0, name: '啊啊啊', file_type: 1 }, ...treeData];
        console.log(aaaa);

        updateSchema({
          field: 'pid',
          componentProps: { aaaa },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '添加分类' : '编辑分类'));

      async function handleSubmit() {
        console.log(rowId, 'rowId');
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          if (!unref(isUpdate)) {
            // 新增
            await createCategory(values).then(() => {
              message.success('添加成功');
            });
          } else {
            // 修改
            values.id = rowId.value;
            await updateCategory(values.id, values).then(() => {
              message.success('修改成功');
            });
          }
          closeModal();
          emit('success', { isUpdate: unref(isUpdate), values });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
